package com.yuandian.customer.perception.controller;

import com.yuandian.api.customer_perception.po.BusinessPerformanceParams;
import com.yuandian.api.customer_perception.po.InterfacePerformanceParams;
import com.yuandian.api.customer_perception.vo.SpecificUserInterfaceVo;
import com.yuandian.api.customer_perception.vo.SpeedRangeVo;
import com.yuandian.api.customer_perception.vo.RelatedBusinessVo;
import com.yuandian.api.customer_perception.vo.InterfaceHealThRateTopVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.InterfacePerformanceService;
import com.yuandian.enums.TableNameEnum;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 说明：接口性能优化controller
 *
 */
@RestController
@RequestMapping("/interfacePerformance")
@Slf4j
public class InterfacePerformanceController {

//    @Autowired
//    private TableShardingService tableShardingService;


    @Autowired
    private InterfacePerformanceService interfacePerformanceService;

//    @Autowired
//    private ICheckTableExistService checkTableExistService;

    /**
     * 查询全部速度区间
     * @param
     * @return List<String>
     */
    @PostMapping("/queryAllSpeedRange")
    public R queryAllSpeedRange(@RequestBody InterfacePerformanceParams params){
        List<SpeedRangeVo> data = interfacePerformanceService.queryAllSpeedRange(params);
        return R.ok(data);
    }

    /**
     * 查询全部接口url
     * @param params(systemId,startTime,endTime)
     * @return List<String>
     */
    @PostMapping("/queryAllUrl")
    public R queryAllUrl(@RequestBody InterfacePerformanceParams params){
       params.setTableName(TableNameEnum.BUSI_STEP_URL_STAT.getName());
        List<String> data = interfacePerformanceService.queryAllUrl(params);
        return R.ok(data);
    }

    /**
     * 查询接口健康度Top10
     * @param params(systemId,startTime,endTime)
     * @return R(interfaceHealThRateTopVo)
     */
    @PostMapping("/queryInterfaceHealthRateTop10")
    public R queryInterfaceHealthRateTop10(@RequestBody InterfacePerformanceParams params) {
		params.setTableName(TableNameEnum.BUSI_STEP_URL_STAT.getName());
        List<InterfaceHealThRateTopVo> data = interfacePerformanceService.queryInterfaceHealthRateTop10(params);
        return R.ok(data);
    }

    /**
     * 查询接口URL运行概况总览
     * @param params(systemId,businessCode,startTime,endTime)
     * @return R()
     */
    @PostMapping("/queryInterfaceURLPerformance")
    public R queryInterfaceURLPerformance(@RequestBody InterfacePerformanceParams params) {
		params.setTableName(TableNameEnum.BUSI_STEP_URL_STAT.getName());
        Map<String, Object> map = interfacePerformanceService.queryInterfaceURLPerformance(params);
        return R.ok(map);
    }

    /**
     * 下载接口URL运行概况总览列表
     * @param params(systemId,businessCode,startTime,endTime)
     * @return
     */
    @PostMapping("/exportInterfaceURLPerformance")
    public void exportInterfaceURLPerformance(@RequestBody InterfacePerformanceParams params,HttpServletResponse response) {
		params.setTableName(TableNameEnum.BUSI_STEP_URL_STAT.getName());
        try {
            interfacePerformanceService.exportInterfaceURLPerformance(params,response);
        } catch (IOException e) {
            log.error("Excel导出异常!");
        }
    }

    /**
     * 查询相关业务列表
     * @param params(businessCodes,startTime,endTime)
     * @return R()
     */
    @PostMapping("/queryRelatedBusiness")
    public R queryRelatedBusiness(@RequestBody InterfacePerformanceParams params){
		params.setTableName(TableNameEnum.KHGZ_BUSI_SYS_DETAIL_STAT.getName());
        List<RelatedBusinessVo> data = interfacePerformanceService.queryRelatedBusiness(params);
        return R.ok(data);
    }

    /**
     * 查询用户操作轨迹列表
     * @param params
     * @return
     */
    @PostMapping("/queryUserOperationTrajectory")
    public R queryUserOperationTrajectory(@RequestBody InterfacePerformanceParams params){
        PageDataInfo data = interfacePerformanceService.queryUserOperationTrajectory(params);
        return R.ok(data);
    }

    /**
     * 下载用户操作轨迹列表
     * @param params
     * @return
     */
    @PostMapping("/exportUserOperationTrajectory")
    public void exportUserOperationTrajectory(@RequestBody InterfacePerformanceParams params,HttpServletResponse response){
        PageDataInfo data = interfacePerformanceService.queryUserOperationTrajectory(params);
        try {
            interfacePerformanceService.exportUserOperationTrajectory(params,response);
        } catch (IOException e) {
            log.error("Excel导出异常!");
        }
    }

    /**
     * 查询具体用户列表
     * @param params
     * @return
     */
    @PostMapping("/querySpecificOperatorList")
    public R querySpecificOperatorList(@RequestBody BusinessPerformanceParams params) {
		params.setTableName(TableNameEnum.BUSI_STEP_URL_STAT.getName());
        return interfacePerformanceService.querySpecificOperatorList(params);
    }

    /**
     * 查询具体用户列表导出
     *
     * @param params 请求参数
     */
    @PostMapping("querySpecificOperatorListExport")
    public void querySpecificOperatorListExport(@RequestBody BusinessPerformanceParams params, HttpServletResponse response) {
        try {
            // 1、查询要导出的数据
            params.setPageNum(1);
            //由于mybatis-plus 分页查询限制 500 条,小于0 如 -1 不受限制
            params.setPageSize(-1);
            PageDataInfo pageDataInfo = BeanUtils.cast(querySpecificOperatorList(params).getData());
            List<SpecificUserInterfaceVo> list = new ArrayList<>();
            try {
                list = BeanUtils.cast(pageDataInfo.getData());
            } catch (Exception e) {
                log.error("所选时间表不存在!但表格需要正常导出.");
            }

            for (SpecificUserInterfaceVo vo : list) {
                vo.setAvgDealTimeStr(vo.getAvgDealTime() == null ? "" : YDateUtil.getMinSecond(getDouble(vo.getAvgDealTime() / 1000)));
                vo.setAvgRequestBytesStr(getData(vo.getAvgRequestBytes()));
                vo.setAvgResponseBytesStr(getData(vo.getAvgResponseBytes()));
            }
            // 2、导出Excel

            //设置表头
            String urlApi = params.getUrlApi();
            String title = "具体用户列表";
            String fileName = title;
            List<String> titleParams = new ArrayList<>();
            titleParams.add(title);
            titleParams.add(params.getSystemName());
            String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());
            List<List<String>> headList = new ArrayList<>();
            List<String> titleList = Arrays.asList("序号","用户标识", "访问量", "平均请求大小", "平均响应大小", "平均处理时长");
            titleList.forEach(s -> {
                List<String> childHeadList = new ArrayList<>();
                childHeadList.add(formTitleName);
                childHeadList.add(s);
                headList.add(childHeadList);
            });
            //回填序号
            int index = 1;
            for (SpecificUserInterfaceVo vo : list) {
                vo.setId(index++);
                if (vo.getOperatorId() == null || vo.getOperatorId().equals("")) {
                    vo.setOperatorId("-");
                }
            }
            ExcelUtil.writeExcel(SpecificUserInterfaceVo.class, fileName, title, list, headList, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询用户操作轨迹趋势图
     * @param params
     * @return
     */
    @PostMapping("/queryOperatorTrajectoryTrend")
    public R queryOperatorTrajectoryTrend(@RequestBody BusinessPerformanceParams params) {
        return interfacePerformanceService.queryOperatorTrajectoryTrend(params);
    }


    /**
     * 查询接口性能变化趋势
     * @param params
     * @return
     */
    @PostMapping("/queryImplementPerformanceTrend")
    public R queryImplementPerformanceTrend(@RequestBody BusinessPerformanceParams params) {

        return interfacePerformanceService.queryImplementPerformanceTrend(params);
    }

    /**
     * 字节单位转换
     * @param data
     * @return
     */
    public static String getData(long data) {
        if (data > 1024*1024){
            BigDecimal b = new BigDecimal((double) data / (1024*1024));
            return b.setScale(2, BigDecimal.ROUND_HALF_UP) + "MB";

        }else if (data > 1024) {
            BigDecimal b = new BigDecimal((double) data / 1024);
            return b.setScale(2, BigDecimal.ROUND_HALF_UP) + "KB";

        }else {
            return data + "B";
        }
    }

    /**
     * 单位转换
     * @param allTime
     * @return
     */
    public static Double getDouble(Double allTime) {
        if (allTime == null) {
            return 0d;
        }
        return new BigDecimal(allTime).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }


}
